package com.thread.xxstudy;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReenLock {

    /**
     * 为公平锁时，加上休眠十秒后，两次的执行顺序是一致的  效率没有非公平锁高，但可以防止‘饥饿’现象
     * 为非公平锁时，两次实行顺序时不一致的
     */
    static Lock lock = new ReentrantLock(true);//true为公平锁  false为非公平锁



 /*   public static void main(String[] args) {
       for (int i = 0; i < 5; i++) {
            new Thread(new ThreadOne(i)).start();
        }
    }*/

    static class ThreadOne extends Thread {
        int id ;
          ThreadOne(int id) {
            this.id = id;
        }
        @Override
        public void run(){

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 2; i++) {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "获取到" + id);
                lock.unlock();
            }
        }


    }

}

